package com.thread.synchromizedDemo;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author milian
 * @Date 2021/7/28 0028 15:54
 */
public class sellTicket implements Runnable {
    private static int tickets = 100;
    private ReentrantLock lock = new ReentrantLock();
    @Override
    public void run() {
        while (true) {

            if ("窗口一".equals(Thread.currentThread().getName())) {
                lock.lock();
                boolean b = synchronizedMethod();
                lock.unlock();
                if (!b){
                    break;
                }
            }
            if ("窗口二".equals(Thread.currentThread().getName())) {
//                synchronized (sellTicket.class) {
                lock.lock();
                try {
                    if (tickets > 0) {
                        Thread.sleep(100);
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
                        tickets--;
                    }else {
                        break;
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    lock.unlock();
                }
//                }
            }
        }
    }

    private static synchronized boolean synchronizedMethod() {
        if (tickets > 0) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "正在出售第" + tickets + "张票");
            tickets--;
            return true;
        }else {
            return false;
        }
    }
}
